<template>
    <div id="registration">
        <div id="header">
            <div style="font-size: 1rem;font-weight: 800;">
                <i class="el-icon-notebook-2" style="color: blue;"></i>用户注册
            </div>
        </div>
        <div id="main">
            <div style="width: 45%;display: flex;justify-content: center;align-items: center;">
                <el-upload action="#" class="avatar-uploader" :auto-upload="false" list-type="picture"
                    :show-file-list="false" :limit="uploadPicNumber" :on-change="onChangeFile">
                    <el-image v-if="!imgUrl" :src="pic()" fit="fill"
                        style="border: 2px dashed red;aspect-ratio: 1 / 1;" />
                    <el-image v-if="imgUrl" :src="imgUrl" fit="fill" style="aspect-ratio: 1 / 1;" />
                    <p>请点击图片上传新内容</p>
                </el-upload>
            </div>
            <hr style="border: 1px solid #b3d8ff;">
            <div style="width: 45%;">
                <el-form :model="user" status-icon ref="userFormRef" :rules="rules" label-width="100px">
                    <el-form-item prop="account" label="账号">
                        <el-input v-model="user.account" :disabled="user.id!== undefined"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label="密码">
                        <el-input v-model="user.password" :disabled="user.id!== undefined"></el-input>
                    </el-form-item>
                    <el-form-item prop="password2" label="确认密码">
                        <el-input v-model="user.password2" :disabled="user.id!== undefined"></el-input>
                    </el-form-item>
                    <el-form-item prop="nickname" label="姓名昵称">
                        <el-input v-model="user.nickname" :disabled="user.id!== undefined"></el-input>
                    </el-form-item>
                    <el-form-item prop="phone" label="电话">
                        <el-input v-model="user.phone" :disabled="user.id!== undefined"></el-input>
                    </el-form-item>
                    <el-form-item label="客户类型">
                        <el-select v-model="user.vip" :disabled="user.id!== undefined">
                            <el-option v-for="i in type" :key="i.v" :label="i.l" :value="i.v">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="addr" label="地址">
                        <el-input type="textarea" v-model="user.addr" :disabled="user.id!== undefined"></el-input>
                    </el-form-item>
                    <el-form-item v-if="user.id === undefined">
                        <el-button size="default" @click="save">
                            <i class="el-icon-user" style="color: red;"></i>
                            <span>注册新用户</span>
                        </el-button>
                    </el-form-item>
                    <el-form-item v-if="user.id!== undefined">
                        <el-button type="success" size="default" @click="goLogin" icon="el-icon-right">前往登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import api from '@/api';
import pic from '@/api/pic';
import { ElMessage } from 'element-plus';
import router from '@/router';


// 响应式变量
const userFormRef = ref(null);
const uploadPicNumber = ref(999);
const imgUrl = ref('');
const fm = ref(new FormData());
const user = reactive({ account: '', password: '', password2: '', phone: '', nickname: '', vip: 0, addr: '' });
const type = [{ v: 0, l: "普通客户" }, { v: 1, l: "vip客户" }];

const valAccount = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('注：请输入账号'));
    } else if (value.length < 3 || value.length > 16) {
        callback(new Error('注：账号长度需为： 3 - 16 个字符'));
    } else {
        callback();
    }
};

const valPassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('注：请输入密码'));
    } else if (value.length < 3 || value.length > 16) {
        callback(new Error('注：账号长度需为： 3 - 16 个字符'));
    } else {
        callback();
    }
};

const valPassword2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('注：确认密码不可为空，与密码一致'));
    } else if (value!== user.password) {
        callback(new Error("注：两次密码输入不一致"));
    } else {
        callback();
    }
};

const valPhone = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('注：请输入手机号'));
    } else if (value.length!== 11) {
        callback(new Error("注：无效号码（长度11位）"));
    } else {
        callback();
    }
};

const valNickname = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('注：请输入您的姓名'));
    } else {
        callback();
    }
};

const valAddr = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('注：请输入您的收货地址'));
    } else {
        callback();
    }
};

const rules = {
    account: [{ validator: valAccount, trigger: 'blur' }],
    password: [{ validator: valPassword, trigger: 'blur' }],
    password2: [{ validator: valPassword2, trigger: 'blur' }],
    phone: [{ validator: valPhone, trigger: 'blur' }],
    nickname: [{ validator: valNickname, trigger: 'blur' }],
    addr: [{ validator: valAddr, trigger: 'blur' }],
};

const goLogin = () => {
    router.push('/login');
};

const onChangeFile = (file, fileList) => {
    console.log("onChangeFile....");
    if (imgUrl.value) {
        imgUrl.value = '';
    }
    if (fm.value.has("mypic")) {
        fm.value.delete("mypic");
    }
    let length = fileList.length - 1;
    if (length >= 0) {
        imgUrl.value = URL.createObjectURL(fileList[length].raw);
        fm.value.append('mypic', fileList[length].raw);
        fileList.length = 0;
    }
};

const save = () => {
    userFormRef.value.validate((valid) => {
        if (valid) {
            if (!fm.value.has("mypic")) {
                ElMessage.warning("头像信息尚未上传");
                return false;
            }
            fm.value.append("account", user.account);
            fm.value.append("password", user.password);
            fm.value.append("phone", user.phone);
            fm.value.append("nickname", user.nickname);
            fm.value.append("vip", user.vip);
            fm.value.append("addr", user.addr);
            api.postf("api/public/user/registration", fm.value).then((resp) => {
            
                if (resp.data.code === 200) {
                    ElMessage.success("修改成功");
                    user.id = resp.data.data;
                    uploadPicNumber.value = 0;
					return
                }
				fm.value = new FormData();
				ElMessage.warning(resp.data.msg)
				
            });
        } else {
            ElMessage.warning("请完成所有选项");
            return false;
        }
    });
};

onMounted(() => {
    user.account = '';
    user.password = '';
    user.password2 = '';
    user.phone = '';
    user.nickname = '';
    user.vip = 0;
    user.addr = '';
});
</script>

<style lang="less" scoped>
#registration {
    min-height: 89vh;
    padding-left: 15%;
    padding-right: 15%;

    #main {
        display: flex;
        justify-content: space-around;
        margin-top: 20px;
        padding-left: 20px;
        padding-right: 20px;
    }

    #header {
        text-align: center;
        padding: 10px 0;
        border-bottom: 1px solid #b3d8ff;
    }
}
</style>    